package ogmios.components;
import javax.swing.*;
import java.awt.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import ogmios.core.*;
/**
 * A JTextPane specially tweaked for use in Ogmios.
 * Does not (yet) allow for word wrap.
 */
public class OgmiosTextPane extends JTextPane
{

  public OgmiosTextPane()
  {
    addCaretListener(
      new CaretListener()
    {
      public void caretUpdate(final CaretEvent e)
      {
        SwingUtilities.invokeLater(
          new Runnable()
        {
          public void run()
          {
            try
            {
              java.awt.Rectangle r = modelToView(getCaretPosition());
              r.x += 2;
              scrollRectToVisible(r);
            }
            catch (Throwable ex)
            {
              OgmiosUtilities.showErrorBox(null, ex, "Code:Caret Error");
            }
          }
        }
        );
      }
    }
    );

  }
  /**
  * Creates the default document to use with OgmiosTextPane
  */
  public Document createDefaultDocument()
  {
    Document document = getEditorKit().createDefaultDocument();
    document.putProperty(DefaultEditorKit.EndOfLineStringProperty, System.getProperty("line.separator"));
    return document;
  }
  public String getText()
  {
    try
    {
      Document doc = getDocument();
      return doc.getText(0, doc.getLength());
    }
    catch (BadLocationException ble)
    {
      return "";
    }
  }
  public boolean getScrollableTracksViewportWidth()
  {
    Component parent = getParent();
    ComponentUI ui = getUI();

    return parent != null ? (ui.getPreferredSize(this).width < parent.getSize().width) : true;
  }

  private boolean selectionOnly;
  /**
  * Prints the current text
  * @param     selectionOnly     Whether to print only the selected text
  */
  public boolean print(boolean selectionOnly) throws java.awt.print.PrinterException
  {
    this.selectionOnly = selectionOnly;
    return print();
  }

  /**
  * Returns the printable form of the text. Do not invoke manually.
  */
  public java.awt.print.Printable getPrintable(final java.text.MessageFormat headerFormat, final java.text.MessageFormat footerFormat)
  {
    if (selectionOnly)
    {
      OgmiosTextPane copy = new OgmiosTextPane();
      copy.setEditorKit(getEditorKit());
      copy.setFont(getFont());
      copy.setForeground(getForeground());
      Document document = copy.createDefaultDocument();
      try
      {
        document.insertString(0, getSelectedText(), null);
      }
      catch (Throwable ex)
      {

      }
      copy.setDocument(document);
      return copy.getPrintable(headerFormat, footerFormat);

    }
    else
    {
      return super.getPrintable(headerFormat, footerFormat);
    }
  }

}
